<template>
  <el-dialog :append-to-body="true" :close-on-click-modal="false" :before-close="cancel" :visible.sync="dialog" :title="isAdd ? '新增' : '编辑'" width="880px">
    <el-card :bordered="false">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="130px">
         <!-- <el-col v-bind="grid2">
            <el-form-item label="线上订单号" prop="orderId">
              <el-input v-model="form.orderId"   />
            </el-form-item>
          </el-col>-->
  <!--        <el-col v-bind="grid2">
            <el-form-item label="用户账户：" prop="uid">
              <el-select v-model="form.uid"  placeholder="请选择" filterable :filter-method="userFilter" clearable >
                <el-option v-for="item in userInfoListShow" :disabled="item.disabled === 0"
                           :value="item.uid" :key="item.uid" :label="item.username" ></el-option>
              </el-select>
            </el-form-item>
          </el-col>-->
        <el-col v-bind="grid2">
       <!--   <el-form-item label="经销商：" prop="distributorId">
            <el-select v-model="form.distributorId"  placeholder="请选择" filterable :filter-method="distributorFilter" clearable >
              <el-option v-for="item in distributorInfoShow" :disabled="item.disabled === 0"
                         :value="item.distributorId" :key="item.distributorId" :label="item.distributorName" ></el-option>
            </el-select>
          </el-form-item>-->
          <el-form-item label="经销商：" prop="distributorName">
            <el-autocomplete v-model="form.distributorName" placeholder="请选择分销商ID" :trigger-on-focus="true"
                             :fetch-suggestions="queryDistributorSearchAsync" @select="handleDistributorSelect">
            </el-autocomplete>
          </el-form-item>
        </el-col>
         <!-- <el-col v-bind="grid2">
            <el-form-item label="用户账户">
              <el-input v-model="form.uid"  />
            </el-form-item>
          </el-col>-->
     <!--     <el-col v-bind="grid2">
            <el-form-item label="买家账号" prop="buyerAccount">
              <el-input v-model="form.buyerAccount"  />
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2"  >
            <el-form-item label="收货人姓名" prop="realName">
              <el-input v-model="form.realName"   />
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2" >
            <el-form-item label="收货人手机" prop="userPhone">
              <el-input v-model="form.userPhone"   />
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="地址" prop="userAddress">
              <el-input v-model="form.userAddress"  />
            </el-form-item>
          </el-col>-->
        <!--<el-form-item label="购物车Id">
          <el-input v-model="form.cardId"  style="width: 180px;" />
        </el-form-item>-->
        <!--<el-form-item label="运费金额">-->
       <!-- </el-form-item>-->
       <!--   <el-col v-bind="grid2">
            <el-form-item label="数量"  prop="totalNum">
              <el-input v-model="form.totalNum" />
            </el-form-item>
          </el-col>-->
       <!--   <el-col v-bind="grid2">
            <el-form-item label="应付金额" prop="payPrice">
              <el-input v-model="form.payPrice" />
            </el-form-item>
          </el-col>-->

  <!--      <el-form-item label="抵扣金额">
          <el-input v-model="form.deductionPrice"  style="width: 370px;" />
        </el-form-item>-->
       <!-- <el-form-item label="优惠券ID">
          <el-input v-model="form.couponId"  style="width: 370px;" />
        </el-form-item>-->
       <!-- <el-form-item label="优惠券金额">
          <el-input v-model="form.couponPrice"  style="width: 370px;" />
        </el-form-item>-->
        <!--<el-form-item label="优惠券金额">
          <el-input v-model="form.couponPrice"  style="width: 370px;" />
        </el-form-item>-->
        <!--<el-form-item label="支付时间">
          <el-input v-model="form.payTime"  style="width: 370px;" />
        </el-form-item>-->
          <!--<el-col v-bind="grid2" >
            <el-form-item label="支付时间" prop="payTime">
              <template>
                <el-date-picker
                  v-model="form.payTime"
                  type="datetime"
                  placeholder="选择日期时间"
                />
              </template>
            </el-form-item>
          </el-col>-->
      <!--    <el-col v-bind="grid2" >
            <el-form-item label="支付方式" prop="payType">
              <el-select @change="selectGet" v-model="form.payType" placeholder="请选择支付方式">
                <el-option
                  v-for="item in selectList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>-->
   <!--     <el-form-item label="创建时间">
          <template>
            <el-date-picker
              v-model="form.createTime"
              type="datetime"
              placeholder="选择日期时间"
            />
          </template>
        </el-form-item>-->
       <!-- <el-form-item label="订单状态">
          <el-input v-model="form.status"  style="width: 370px;" />
        </el-form-item>-->
        <!--  <el-col v-bind="grid2" >
            <el-form-item label="订单状态"  prop="status">
             &lt;!&ndash; <el-input v-model="form.status"  value="3" />&ndash;&gt;
              <el-select @change="selectGet" v-model="form.status" placeholder="请选择订单状态">
                <el-option
                  v-for="item in statusList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>-->
       <!--   <el-col v-bind="grid2"  >
            <el-form-item label="快递公司编码" >
              <el-input v-model="form.deliverySn"/>
            </el-form-item>
          </el-col>-->
     <!--     <el-col v-bind="grid2">
            <el-form-item label="商品名称：" prop="productId">
              <el-autocomplete v-model="form.productId"  placeholder="请选择"  :trigger-on-focus="false" :fetch-suggestions="querySearchAsync" @select="handleSelect">
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2" >
            <el-form-item label="快递名称" >
              <el-input v-model="form.deliveryName" />
            </el-form-item>
          </el-col>-->
       <!--   <el-col v-bind="grid2">
            <el-form-item label="商品名称"  prop="storeName">
              <el-input v-model="form.storeName" />
            </el-form-item>
          </el-col>-->
        <!--  <el-col v-bind="grid2">
            <el-form-item label="颜色及规格"  prop="sku">
              <el-input v-model="form.sku" />
            </el-form-item>
          </el-col>-->
        <!--  <el-col v-bind="grid2">
            <el-form-item label="颜色及规格：" prop="attrId">
            <el-select v-model="form.attrId"  placeholder="请选择" filterable :filter-method="dataFilter" clearable >
                <el-option v-for="item in productSkuInfoShow" :disabled="item.disabled === 0"
                           :value="item.id" :key="item.id" :label="item.sku" ></el-option>
            </el-select>
            </el-form-item>
          </el-col>-->
        <!--  <el-col v-bind="grid2">
            <el-form-item label="商品条码"  prop="barCode">
              <el-input v-model="form.barCode" />
            </el-form-item>
          </el-col>-->

      <!--  <el-form-item label="发货类型">
          <el-input v-model="form.deliveryType"  style="width: 370px;" />
        </el-form-item>-->
       <!--   <el-col v-bind="grid2">
            <el-form-item label="快递单号">
              <el-input v-model="form.deliveryId" />
            </el-form-item>
          </el-col>-->
       <!-- <el-form-item label="使用积分">
          <el-input v-model="form.gainIntegral"  style="width: 370px;" />
        </el-form-item>-->
       <!-- <el-form-item label="实际支付积分">
          <el-input v-model="form.useIntegral"  style="width: 370px;" />
        </el-form-item>-->
       <!-- <el-form-item label="给用户退了积分">
          <el-input v-model="form.backIntegral"  style="width: 370px;" />
        </el-form-item>-->
   <!--       <el-col v-bind="grid2" >
            <el-form-item label="买家留言" prop="mark">
              <el-input v-model="form.mark"  />
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2" >
            <el-form-item label="卖家备注" prop="remark">
              <el-input v-model="form.remark"  />
            </el-form-item>
          </el-col>-->
       <!-- <el-form-item label="唯一ID">
          <el-input v-model="form.unique"  style="width: 370px;" />
        </el-form-item>-->
   <!--     <el-form-item label="管理员备注">
          <el-input v-model="form.remark"  style="width: 370px;" />
        </el-form-item>
        <el-form-item label="商户ID">
          <el-input v-model="form.merId"  style="width: 370px;" />
        </el-form-item>-->
        <!--<el-form-item>
          <el-input v-model="form.cost" value="0.0" type="hidden" style="width: 370px;" label="成本价"/>
        </el-form-item>-->
       <!-- <el-form-item label="配送方式">
          <el-input v-model="form.shippingType"  style="width: 370px;" />
        </el-form-item>-->
        <!--  <el-col v-bind="grid2">
            <el-form-item label="分销商ID">
              <el-input v-model="form.distributorId"  />
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="分销商名称">
              <el-input v-model="form.distributorName" />
            </el-form-item>
          </el-col>-->
        <!--<el-form-item label="订单总价">-->
        <el-input v-model="form.totalPrice"  :value="form.payPrice" type="hidden" />
        <!--  </el-form-item>-->
        <el-input v-model="form.freightPrice" type="hidden" :value="0" />
        <!--<el-form-item label="支付状态">-->
        <el-input v-model="form.paid"  :value="0" type="hidden" />
         <!-- <el-form-item label="是否删除">-->
        <el-input v-model="form.isDel" type="hidden" :value="0" />
          <!--</el-form-item>-->
        <!--</el-form-item>-->
        <el-row :gutter="24">
          <el-col v-bind="grid2">
          <el-form-item>
            <el-button @click="addDomain">新增</el-button>
            <!--  <el-button @click="resetForm('dynamicValidateForm')">重置</el-button>-->
          </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
            <el-form-item v-for="(product, index) in this.productShoppingCartInfo.products" :label="'购买商品'+ index+':'" :key="product.key">
              <el-col v-bind="grid2">
              <el-autocomplete v-model="product.productId"  placeholder="请选择商品"  :trigger-on-focus="false" :fetch-suggestions="querySearchAsync" @select="handleSelectByProductId(product)">
              </el-autocomplete>
              </el-col>
              <el-col v-bind="grid2">
              <el-select v-model="product.attrId"  placeholder="请选择商品规格" filterable :filter-method="dataFilter" clearable >
                <el-option v-for="item in product.productSkuInfoShow" :disabled="item.disabled === 0"
                           :value="item.id" :key="item.id" :label="item.sku" ></el-option>
              </el-select>
              </el-col>
              <el-col v-bind="grid2">
                <el-input v-model="product.num" placeholder="商品数量,请输入数字" oninput="value=value.replace(/[^\d]/g,'')"/>
              </el-col>
              <el-col v-bind="grid2">
              <el-button @click.prevent="removeDomain(product)">删除</el-button>
              </el-col>
            </el-form-item>
        </el-row>
      </el-form>
    </el-card>

    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>

</template>

<script>
import { add } from '@/api/yxStoreOrder'
import {addOrder,getProductInfo,getSkuInfo,getUserInfo,getDistributorInfo} from '@/api/yxStoreOrder';
export default {
  props: {
    isAdd: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      dynamicValidateForm: {
        domains: [{
          value: ''
        }],
        email: ''
      },
      productShoppingCartInfo:{
        products:[
          {
            productId:'',
            attrId:'',
            num:'',
            key: Date.now(),
            productSkuInfoShow:[]
          }
        ]
      },
      treeSelect: [],
      optionsMetaShow:[],
      attrValues:[],
      attrResults:[],
      productList:[],
      productInfo:[],
      productInfoShow:[],
      productId:'',
      productSkuInfo:[],
      productSkuInfoShow:[],
      userInfoList:[],
      userInfoListShow:[],
      distributorInfoList:[],
      distributorInfoShow:[],
      product:{},
      loading: false, dialog: false,
      form: {
        products:[],
        id: '',
        orderId: '',
        uid: '',
        attrId:'',
        buyerAccount:'',
        realName: '',
        userPhone: '',
        userAddress: '',
        cartId: '',
        freightPrice: '',
        totalNum: '',
        totalPrice: '',
        totalPostage: '',
        payPrice: '',
        payPostage: '',
        deductionPrice: '',
        couponId: '',
        couponPrice: '',
        paid: '',
        payTime: '',
        payType: '',
        addTime: '',
        status: '',
        refundStatus: '',
        refundReasonWapImg: '',
        refundReasonWapExplain: '',
        refundReasonTime: '',
        refundReasonWap: '',
        refundReason: '',
        refundPrice: '',
        deliveryName: '',
        deliveryType: '',
        deliveryId: '',
        gainIntegral: '',
        useIntegral: '',
        backIntegral: '',
        mark: '',
        isDel: '',
        unique: '',
        remark: '',
        merId: '',
        isMerCheck: '',
        combinationId: '',
        pinkId: '',
        cost: '',
        seckillId: '',
        bargainId: '',
        verifyCode: '',
        storeId: '',
        shippingType: '',
        isChannel: '',
        isRemind: '',
        isSystemDel: '',
        distributorId: '',
        distributorName:'',
        tel:'',
        storeName:'',
        sku:'',
        barCode:''
      },
      rules: {
        orderId: [
          {  required: true, message: '请输入线上订单号', trigger: 'blur'}
        ],
        realName: [
          {  required: true, message: '请输入收货人姓名', trigger: 'blur'}
        ],
        userAddress: [
          {  required: true, message: '请输入收货人地址', trigger: 'blur'}
        ],
        payTime: [
          {  required: true, message: '请输入支付时间', trigger: 'blur'}
        ],
        payType: [
          {  required: true, message: '请输入支付方式', trigger: 'blur'}
        ],
        mark: [
          {  required: true, message: '请输入买家留言', trigger: 'blur'}
        ],
        remark: [
          {  required: true, message: '请输入卖家备注', trigger: 'blur'}
        ],
        storeName: [
          {  required: true, message: '请输入商品名称', trigger: 'blur'}
        ],
        sku: [
          {  required: true, message: '请输入商品规格', trigger: 'blur'}
        ],
        totalNum: [
          {  required: true, message: '请输入数量', trigger: 'blur'}
        ],
        userPhone: [
          {  required: true, message: '请输入手机号', trigger: 'blur'}
        ],
        payPrice: [
          {  required: true, message: '请输入应付金额', trigger: 'blur'}
        ],
        buyerAccount: [
          {  required: true, message: '请输入应付金额', trigger: 'blur'}
        ],
        uid: [
          {  required: true, message: '请输入用户账号', trigger: 'blur'}
        ],
        productId: [
          {  required: true, message: '请输入商品名称', trigger: 'blur'}
        ],
        attrId: [
          {  required: true, message: '请输入颜色及规格', trigger: 'blur'}
        ],
      },
      selectList:[
        {id:1,name:'支付宝'},
        {id:2,name:'微信'},
        {id:3,name:'银行卡'}
      ],
      statusList:[
        {id:0,name:'待发货'},
        {id:1,name:'待收货'},
        {id:2,name:'已收货'},
        {id:3,name:'已完成'},
        {id:-1,name:'已退款'}
      ],
      grid2: {
        xl: 10,
        lg: 12,
        md: 12,
        sm: 24,
        xs: 24
      },
    }
  },
  mounted () {
    this.getProductInfo();
    this.getUserInfo();
    this.getDistributorInfo();
  },
  methods: {
    // 删除
    removeDomain(item) {
      var index = this.productShoppingCartInfo.products.indexOf(item)
      if (index !== -1) {
        this.productShoppingCartInfo.products.splice(index, 1)
      }
    },
    // 新增
    addDomain() {
      this.productShoppingCartInfo.products.push({
        productId:'',
        attrId:'',
        num:'',
        key: Date.now(),
        productSkuInfoShow:[]
      });
    },
    dataFilter(val){
      this.value=val
      if(val){
        this.form.attrId = val
        this.optionsMetaShow=this.treeSelect.filter((item=>{
          if (!!~item.label.indexOf(val) || !!~item.label.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          }
        }))
      }else{
        this.optionsMetaShow=this.treeSelect
      }
    },
    userFilter(val){
      this.value=val
      if(val){
        this.form.uid = val
        this.userInfoListShow=this.userInfoList.filter((item=>{
          if (!!~item.username.indexOf(val) || !!~item.username.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          }
        }))
      }else{
        this.userInfoListShow=this.userInfoList
      }
    },
    distributorFilter(val){
      this.value=val
      if(val){
        this.form.distributorId = val
        this.distributorInfoShow=this.distributorInfoList.filter((item=>{
          if (!!~item.distributorName.indexOf(val) || !!~item.distributorName.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          }
        }))
      }else{
        this.distributorInfoShow=this.distributorInfoList
      }
    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {

      // if(!this.form.orderId || !this.form.realName || !this.form.userPhone
      //   || !this.form.payType || !this.form.mark
      //   || !this.form.storeName || !this.form.buyerAccount){
      // console.log(this.form.product)
      /*if(!this.form.productId || !this.form.attrId || !this.form.totalNum || !this.form.uid){
        this.$message.warning("请填写完整商品信息！");
      } else {
        this.loading = true
        this.doAdd()
      }*/
      this.form.products =  this.productShoppingCartInfo.products
      this.doAdd()
    },
    doAdd() {
      addOrder(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },

    querySearchAsync(queryString, cb) {
      //在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示，所以我从新封装了
      let productList = this.productList;
      // console.log(productList)

      let programList = [];
      for(let i=0;i<this.productList.length;i++){
        programList.push({'value':productList[i].id +'--'+productList[i].storeName})
      }
      // console.log(programList.values())
      let results = queryString ? programList.filter(this.createStateFilter(queryString)) : programList;
      //基本思路就是实现一个过滤器，过滤存在你输入字段的所有数据。
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
    },createStateFilter(queryString) {
      return (product) => {
        return (product.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
      };
    },handleSelect(item) {
      // this.form.productId = item.value
      var strs= new Array();
      strs = item.value.split("--")
      this.productId = strs[0]
      this.getSkuInfo()
    },
    handleSelectByProductId(item) {
      // this.form.productId = item.value
      var strs= new Array();
      strs = item.productId.split("--")
      this.productId = strs[0]
      this.getSkuInfoByProductId(item)
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.form = {
        id: '',
        orderId: '',
        attrId:'',
        uid: '',
        realName: '',
        userPhone: '',
        userAddress: '',
        cartId: '',
        freightPrice: '',
        totalNum: '',
        totalPrice: '',
        totalPostage: '',
        payPrice: '',
        payPostage: '',
        deductionPrice: '',
        couponId: '',
        couponPrice: '',
        paid: '',
        payTime: '',
        payType: '',
        addTime: '',
        status: '',
        refundStatus: '',
        refundReasonWapImg: '',
        refundReasonWapExplain: '',
        refundReasonTime: '',
        refundReasonWap: '',
        refundReason: '',
        refundPrice: '',
        deliveryName: '',
        deliveryType: '',
        deliveryId: '',
        gainIntegral: '',
        useIntegral: '',
        backIntegral: '',
        mark: '',
        isDel: '',
        unique: '',
        remark: '',
        merId: '',
        isMerCheck: '',
        combinationId: '',
        pinkId: '',
        cost: '',
        seckillId: '',
        bargainId: '',
        verifyCode: '',
        storeId: '',
        shippingType: '',
        isChannel: '',
        isRemind: '',
        isSystemDel: '',
        tel:'',
        storeName:''
      }
    },
    selectGet(vId){
      let obj = {};
      obj = this.selectList.find((item)=>{//这里的selectList就是上面遍历的数据源
        return item.id === vId;//筛选出匹配数据
      });
    },
    // 商品详情
    getProductInfo() {
      let that = this;
      getProductInfo().then(async res => {
        let data = res.productList;
        if(data) {
          this.attrs = data.items || [];
          that.form.product = data;
          that.treeSelect = res.productList;
          that.productList = res.productList
          that.optionsMetaShow = that.treeSelect
        }
      }).catch(res => {
        return this.$message({
          message:res.msg,
          type: 'error'
        });
      })
    },
    // sku 详情
    getSkuInfo() {
      let that = this;
      let id = that.productId;
      getSkuInfo(id).then(async res => {
        let data = res.attrValues;
        if(data){
          that.form.productSkuInfo = data;
          that.productSkuInfo = res.productSkuInfo
          that.productSkuInfoShow  = res.attrValues
        }
      }).catch(res => {
        return this.$message({
          message:res.msg,
          type: 'error'
        });
      })
    },
    getSkuInfoByProductId(item) {
      var strs= new Array();
      strs = item.productId.split("--")
      let id = strs[0]
      getSkuInfo(id).then(async res => {
        let data = res.attrValues;
        if(data){
          item.productSkuInfoShow = res.attrValues
        }
      }).catch(res => {
        return this.$message({
          message:res.msg,
          type: 'error'
        });
      })
    },
    getUserInfo() {
      let that = this;
      getUserInfo().then(async res => {
        let data = res.userInfoList;
        console.log("data", res.userInfoList)
        if(data) {
          console.log("data", res.userInfoList)
          that.userInfoListShow = res.userInfoList;
        }
      }).catch(res => {
        // console.log('err:'+res)
        return this.$message({
          message:res.msg,
          type: 'error'
        });
      })
    },
    getDistributorInfo(){
      let that = this;
      getDistributorInfo().then(async res => {
        let data = res.distributorInfoList;
        // console.log("data", res.distributorInfoList)
        if(data) {
          // console.log("data", res.distributorInfoList)
          that.distributorInfoList = res.distributorInfoList
          that.distributorInfoShow = res.distributorInfoList;
        }
      }).catch(res => {
        return this.$message({
          message:res.msg,
          type: 'error'
        });
      })
    },
    queryDistributorSearchAsync(queryString, cb) {
      debugger
      //在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示，所以我从新封装了
      let distributorInfoList = this.distributorInfoList;

      let programList = [];
      for (let i = 0; i < this.distributorInfoList.length; i++) {
        programList.push({'value': distributorInfoList[i].distributorId + '--' + distributorInfoList[i].distributorName})
      }
      let results = queryString ? programList.filter(this.createStateFilter(queryString)) : programList;
      //基本思路就是实现一个过滤器，过滤存在你输入字段的所有数据。
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000 * Math.random());
    }, handleDistributorSelect(item) {
      var strs = new Array();
      // console.log("item:"+item.value.distributorId)
      strs = item.value.split("--")
      this.form.distributorId = strs[0]
      this.form.distributorName = strs[1]
    },

  }
}
</script>

<style scoped>

</style>
